package com.dz.goods.service;

import com.dz.common.base.BasePageResultsVO;
import com.dz.common.constants.CodeDomain;
import com.dz.goods.domain.entity.Album;
import com.dz.goods.domain.entity.Brand;
import com.dz.goods.domain.entity.QAlbum;
import com.dz.goods.domain.repository.AlbumRepository;
import com.dz.goods.domain.vo.AlbumParamsVO;
import com.dz.goods.domain.vo.AlbumResultsVO;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class AlbumServiceImpl implements AlbumService{

    @Autowired
    private AlbumRepository albumRepository;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Override
    @Transactional
    public Album findById(Long id) {
        return albumRepository.findById(id).get();
    }

    @Override
    @Transactional
    public Album add(Album album) {
        return albumRepository.saveAndFlush(album);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        Album album = albumRepository.findById(id).get();
        album.setDeleteFlag(Integer.valueOf(CodeDomain.DELETE_FLAG_YES.value()));
        albumRepository.saveAndFlush(album);
    }
    @Transactional
    @Override
    public Album edit(Album album) {
        return albumRepository.saveAndFlush(album);
    }
    @Transactional
    @Override
    public BasePageResultsVO<AlbumResultsVO> getAlbumList(AlbumParamsVO vo) {
        QAlbum album=QAlbum.album;
        BooleanBuilder where=new BooleanBuilder();
        if(StringUtils.isNotEmpty(vo.getId())){
            where.and(album.id.eq(Long.parseLong(vo.getId())));
        }
        if(StringUtils.isNotEmpty(vo.getTitle())){
            where.and(album.title.eq(vo.getTitle()));
        }
        where.and(album.deleteFlag.eq(Integer.valueOf(CodeDomain.DELETE_FLAG_NO.value())));
        JPAQuery<Album> query=jpaQueryFactory.select(album).from(album).where(where.getValue());
        QueryResults<Album> fetchResults = query.offset((vo.getPageNum() - 1L) * vo.getPageSize()).limit(vo.getPageSize()).fetchResults();
        List<AlbumResultsVO> list = fetchResults.getResults().stream().map(e -> AlbumResultsVO.builder().id(e.getId())
                .title(e.getTitle())
                .imageItems(e.getImageItems())
                .build()).collect(Collectors.toList());
        return BasePageResultsVO.success(vo.getPageNum(),vo.getPageSize(),fetchResults.getTotal(),list);
    }
}